package Page.LoginAndExitRecordPage;

import Controller.MainController;
import Controller.User.UserType;
import Dao.LoginAndExitRecordDao;
import DataClass.LoginAndExit;
import Setting.Setting;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;

import java.net.URL;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class InAndOutController implements Initializable {

    @FXML
    public Button BackButton;
    @FXML
    public TableView<LoginAndExit> InAndOutTable;
    @FXML
    public TableColumn<LoginAndExit,String> ruId;
    @FXML
    public TableColumn<LoginAndExit,Integer> infoId;
    @FXML
    public TableColumn<LoginAndExit,String> infoType;
    @FXML
    public TableColumn<LoginAndExit, Timestamp> infoInTime;
    @FXML
    public TableColumn<LoginAndExit, Timestamp> infoOutTime;
    @FXML
    public TableColumn<LoginAndExit, String> ruTeacher;
    @FXML
    public TableColumn<LoginAndExit, String> ruAnoTeacher;
    @FXML
    public TableColumn<LoginAndExit, String> ruName;

    @FXML
    public Button ClearButton;
    @FXML
    public TextField InputPeople;
    @FXML
    public Button FindButton;
    @FXML
    public Button RefreshButton;
    @FXML
    public DatePicker InputData;
    @FXML
    public javafx.scene.control.Pagination Pagination;

    private InAndOutViewModel viewModel;

    // 每一页数据数量
    private final static int rowsPerPage = Setting.ItemsPerPage;

    //=========================================================================================================
    // init

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        viewModel = new InAndOutViewModel();

        ruId.setCellValueFactory(new PropertyValueFactory<>("RUid"));
        infoId.setCellValueFactory(new PropertyValueFactory<>("InfoId"));
        infoType.setCellValueFactory(new PropertyValueFactory<>("InfoType"));
        infoInTime.setCellValueFactory(new PropertyValueFactory<>("InfoInTime"));
        infoOutTime.setCellValueFactory(new PropertyValueFactory<>("InfoOutTime"));
        ruTeacher.setCellValueFactory(new PropertyValueFactory<>("RUTeacher"));
        ruAnoTeacher.setCellValueFactory(new PropertyValueFactory<>("RUAnoTeacher"));
        ruName.setCellValueFactory(new PropertyValueFactory<>("RPName"));

        InputPeople.textProperty().bindBidirectional(viewModel.getInputId());
        InputPeople.textProperty().addListener((observable, oldValue, newValue) -> {
            viewModel.updateInputId(newValue);
        });
        InputData.valueProperty().bindBidirectional(viewModel.getInputDate());
        InputData.valueProperty().addListener((observable, oldValue, newValue) -> {
            viewModel.updateInputDate(newValue);
        });

        if(MainController.getUserType() == UserType.MANAGER)
        {
            try{
                // 通过当前名称获取信息
                viewModel.setDataList(LoginAndExitRecordDao.getLoginAneExitRecord());
            } catch (SQLException e) {
                viewModel.setDataList(new ArrayList<>());
                System.err.println("LoginAndOut 数据获取失败 in InAndOutController");
            }
        }else{
            try{
                // 通过当前名称获取信息
                viewModel.setDataList(LoginAndExitRecordDao.getLoginAneExitRecordWithTeacherName(MainController.getCurrentUsrName()));
            } catch (SQLException e) {
                viewModel.setDataList(new ArrayList<>());
                System.err.println("LoginAndOut 数据获取失败 in InAndOutController");
            }
        }

        this.initPagination();

        viewModel.getDataListProperty().addListener((ov, oldValue, newValue) -> {
            this.refreshPagination();
        });
    }
    //=========================================================================================================
    // pagination

    private void initPagination(){
        this.refreshPagination();
    }
    /**
     * @since 2024-06-04
     * @param pageIndex 当前页面索引
     * @return TableView
     */
    private TableView<LoginAndExit> createPage(int pageIndex) {
        int lastIndex = Math.min(pageIndex * rowsPerPage + rowsPerPage, viewModel.getDataListProperty().size());
        int displace = pageIndex * rowsPerPage;
        ObservableList<LoginAndExit> pageData = FXCollections.observableArrayList(viewModel.getDataListProperty().subList(displace, lastIndex));

        InAndOutTable.setItems(pageData);
        return InAndOutTable;
    }

    /**
     * 重载分页器
     */
    public void refreshPagination(){
        Pagination.setPageCount((viewModel.getDataListProperty().size()/rowsPerPage +1 ));
        Pagination.setPageFactory(this::createPage);
        Pagination.setCurrentPageIndex(0);
    }



    //=========================================================================================================
    // click event

    public void backButtonOnAction(javafx.event.ActionEvent actionEvent) {
        viewModel.backButtonClicked();
    }

    public void refreshButtonClicked(ActionEvent actionEvent) {
        viewModel.refresh();
        try{
            viewModel.setDataList(LoginAndExitRecordDao.getLoginAneExitRecord());
        } catch (SQLException e) {
            viewModel.setDataList(new ArrayList<>());
            System.err.println("LoginAndOut 数据获取失败 in InAndOutController");
        }
    }

    public void clearButtonClicked(ActionEvent actionEvent) {
        viewModel.clearFilter();
    }

    public void findButtonClicked(ActionEvent actionEvent) {
        viewModel.findButtonClicked();
    }
}